package com.example.petcare.service.serviceImpl;

import com.example.petcare.mapper.CartItemMapper;
import com.example.petcare.mapper.GoodsMapper;
import com.example.petcare.mapper.HostMapper;
import com.example.petcare.pojo.CartItem;
import com.example.petcare.pojo.Goods;
import com.example.petcare.pojo.HostDemand;
import com.example.petcare.service.CartItemService;
import com.example.petcare.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class CartItemServiceImpl implements CartItemService {
    @Autowired
    private CartItemMapper cartItemMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private HostMapper hostMapper;



    // 计算hostId下的委托和增值商品的价格，插入到price表中
    @Override
    public void updateTotalPrice(Integer hostId) {
        // 先查询购物车中所有的增值商品
        List<CartItem> cartItems = cartItemMapper.getCartItemsByHostId(hostId);
        Double totalPrice = 0.0;

        // 遍历购物车中的增值商品,根据里面的gId查询增值商品的价格
        for (CartItem cartItem : cartItems) {
            Integer gId = cartItem.getGId();
            Goods goods = goodsMapper.findById(gId);
            // 计算购物车总价
            totalPrice += goods.getPrice();
        }

        // 根据hostId查询托管需求
        HostDemand hostDemand = hostMapper.findById(hostId);
        // 获取里面的providerId和price
        Integer providerId = hostDemand.getProviderId();
        // 获取托管需求的价格
        Double hostPrice = hostDemand.getPrice();

        // 计算总价
        Double total = totalPrice + hostPrice;


        // 用providerId查询price表中的price数据
        // 如果有数据就更新
        // 先查询price表中是否有数据
        Double price = cartItemMapper.findPriceByProviderId(providerId);

        // 先判断price是否为null
        if (price == null) {
            // 如果为null,说明没有
        }

        price = price + total;

        // 将price更新到price表中
        cartItemMapper.updatePriceByProviderId(providerId, price);



    }

    // 查询price表中的price数据
    @Override
    public Double findPriceByProviderId() {

        // 从threadlocal中获取providerId
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer providerId = (Integer) map.get("ProviderId");
        // 如果是管理员，上面就获取不到providerId，所以再获取一次
        if(providerId == null){
            providerId = (Integer) map.get("AdminId");
        }
        Double price = cartItemMapper.findPriceByProviderId(providerId);
        return price;
    }
}
